from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from django.http import HttpResponse
import random
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView

from . import constants
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.yuntongxun.sms import CCP

from .serializer import ImageCodeCheckSerializer
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.


# 图片验证码实现
class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        """
        获取图片验证码,参数是uuid
        """
        # 生成验证码图片
        text, image = captcha.generate_captcha()
        print(text)

        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="images/jpg")


# 短信验证码
class SmsCodeView(GenericAPIView):
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        # 创建序列化器对象
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # 保存短信验证码与发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        # 发送短信
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES//60], 1)   # 5分钟和redis中的图片验证码时间一样
        # delay 将延时任务添加到任务队列,触发任务队列,worker观察到
        send_sms_code.delay(mobile, sms_code)
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        return Response({'message': 'OK'})